package com.songlanyun.modules.rabbitmq.mq.consumer;

import com.rabbitmq.client.Channel;
import com.songlanyun.common.enums.OrderConstant;
import com.songlanyun.common.utils.custom.ClassConvertUtils;
import com.songlanyun.modules.order.service.OrderOperationService;
import com.songlanyun.modules.payorder.entity.PayOrder;
import com.songlanyun.modules.payorder.service.PayOrderService;
import com.songlanyun.modules.rabbitmq.DelayedConstant;
import com.songlanyun.modules.refillorder.service.SaleRefillCardOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class OrderExpireConsumer extends BaseConsumer {
    @Autowired
    private PayOrderService payOrderService;

    @Autowired
    private SaleRefillCardOrderService saleRefillCardOrderService;

    @Autowired
    private OrderOperationService orderOperationService;

    @Override
    protected void process(Message message) {
        Long orderId = ClassConvertUtils.objToLong(new String(message.getBody()));
        PayOrder v = payOrderService.getById(orderId);
        try {
            log.info(String.format("支付订单:%s 过期，开始执行自动撤单", v.getCode()));
            if (v.getOrderType().equals(OrderConstant.OrderType.REFILL_ORDER)) {
                //充值订单 关闭
                saleRefillCardOrderService.closeOrder(v.getId());
            }
            else
            {
                //消费订单 服务订单
                orderOperationService.payExpireCancel(v.getId());
            }

            log.info(String.format("支付订单:%s 过期，完成执行自动撤单", v.getCode()));
        }
        catch (Exception ex) {
            log.error(String.format("支付订单:%s 过期，执行自动撤单,出错%s", v.getCode(), ex.getMessage()));
            throw  ex;
        }
    }

    @RabbitListener(queues = DelayedConstant.OrderDelayedConstant.ORDER_DELAYED_QUEUE)
    public void consume(Message message, Channel channel) throws IOException {
        super.handle(message,channel);
    }
}
